import {useRoute, useRouter} from "vue-router";
import useUserStore from '@/store/modules/user'


const TokenKey = 'Authentication'

export const getCurrentRouteAuth = () => {
  const route = useRoute()
  try {
    let idx=route.matched[0].children.findIndex(r => r.path === route.path)
    return route.matched[0].children[idx].auth;   
  } catch (e) {
    console.log(e)
    return []
  }
}
// 表格编辑权限
export const hasTableEditAuth =(value)=>{
  const roleName = useUserStore().GetInfo().roleName 
  const permissions = useUserStore().GetInfo().permissions;
  if(roleName == '超级管理员'||roleName == 'super'){
    return true;
  } 
  return permissions.includes(value)
};
export const getRouteAuth = (path) => {
  const router = useRouter().getRoutes()
  try {
    return router.find(n=>n.path.includes(path) && n.redirect).children[0].auth
  } catch (e) {
    console.log(`不存在相应权限：${path}-${e.message}`)
    return []
  }
}

export const hasAuth = (auth, key) => {
  if (!auth) return []
  return auth.some(n => n.name == key)   
}

export function getToken() {
  return localStorage.getItem(TokenKey)
}

export function setToken(token) {
  return localStorage.setItem(TokenKey, token)
}

export function getUser() {
  const userInfo = localStorage.getItem('user')
  return userInfo && userInfo.includes('{') ? JSON.parse(userInfo) : null
}

export function setUser(user) {
  return localStorage.setItem('user', user)
}

export function setRemeber(remeber) {
  return localStorage.setItem('remeber', remeber)
}

export function removeToken() {
  return localStorage.removeItem(TokenKey)
}

export function removeUser() {
  return localStorage.removeItem('user')
}

export function removeRemeber() {
  return localStorage.removeItem('remeber')
}
